# coding=utf8

import os
from docx import Document
from docxcompose.composer import Composer
from win32com import client


def compose_docx(path, files, save_file):
    """
    raise KeyError None
    :param path:
    :param files:
    :param save_file:
    :return:
    """
    path_files = []
    for file_name in files:
        path_files.append(path + file_name)
    doc0 = Document(path_files[0])
    doc0.add_page_break()
    merge_doc = Composer(doc0)
    num = 0
    for pf in path_files:
        print(pf)
        if num == 0:
            num += 1
            continue
        doc = Document(pf)
        doc.add_page_break()
        merge_doc.append(doc)
        # try:
        #     merge_doc.append(doc)
        # except KeyError as e:
        #     print(e)
        # except Exception as e:
        #     print(e)
        num += 1
        if num == 3:
            break
    merge_doc.save(save_file)


def merge_docx1(docx_path, docx_files, docx_merge):
    word = client.gencache.EnsureDispatch("Word.Application")
    word.Visible = False
    new_doc = word.Documents.Add()
    for f in docx_files:
        # read file to shear plate
        temp_doc = word.Documents.Open(os.path.join(docx_path, f))
        word.Selection.WholeStory()
        word.Selection.Copy()
        temp_doc.Close()
        # paste
        new_doc.Range()
        word.Selection.Delete()
        word.Selection.Paste()
    new_doc.SaveAs(docx_merge)
    new_doc.Close()
    word.Quit()


def merge_docx2(docx_path, docx_files, docx_merge):
    word = client.gencache.EnsureDispatch("Word.Application")
    word.Visible = False
    new_doc = word.Documents.Add()
    for f in docx_files[::-1]:
        fabs = os.path.join(docx_path, f)
        new_doc.Application.Selection.Range.InsertFile(fabs)
    new_doc.SaveAs(docx_merge)
    new_doc.Close()
    word.Quit()


def merge_docx3(path, files, save_file):
    """
    can only merge pure text
    some special chars fail to merge
    """
    save_doc = Document()
    for index, f in enumerate(files):
        print(f)
        doc = Document(path+f)
        for element in doc.element.body:
            save_doc.element.body.append(element)
    save_doc.save(save_file)


def rename_docs():
    files = os.listdir(doc_path)
    for f in files:
        if '--task' in f:
            _f = doc_path+f
            os.rename(_f, _f.replace("ch", "第").replace('--task', '章--任务'))
            print(f)


if __name__ == '__main__':
    dir1 = "f:/mywrite/Python国规教材/数据应用与服务初级/levelpdraft1/"
    dir2 = 'd:/wxc/成稿/level1bak20220107/'
    doc_path = dir1 if os.path.isdir(dir1) else dir2

    mdir1 = 'd:/wxc/成稿/Level1merge0107'
    mdir2 = "f:/mywrite/Python国规教材/数据应用与服务初级/Level1merge0107"
    mdir = mdir1 if os.path.isdir(mdir1) else mdir2
    merge_file1 = mdir + 'A.docx'
    merge_file2 = mdir + 'B.docx'

    doc_files = os.listdir(doc_path)
    # doc_files = doc_files[3:]

    # merge_docx()
    # compose_docx()
    # rename_docs()

    # test Fail: pywintypes.com_error: (-2147352567, '发生意外。', (0, 'Microsoft Word', '文件可能已经损坏。', ...
    merge_docx2(doc_path, doc_files, merge_file1)
